/**
 * @Author: lclangcheng
 * @Date:   2018-08-20 15:11:43
 * @Email:  lclangcheng@gmail.com
 * @Filename: utils.js
 * @Last modified by:   lclangcheng
 * @Last modified time: 2018-10-15 18:19:17
 * @License: jin10
 * @Copyright: jin10
 */
'use strict'
const crypto = require('crypto')
const moment = require('moment')
// var mp3Duration = require('mp3-duration')

var utils = module.exports = {}

/**
* 处理对象参数值，排除对象参数值为”“、null、undefined，并返回一个新对象
**/
utils.dealObjectValue = (obj) => {
  var param = {}
  if (obj === null || obj === undefined || obj === '') return param
  for (var key in obj) {
    if (utils.dataType(obj[key]) === 'Object') {
      param[key] = utils.dealObjectValue(obj[key])
    } else if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
      param[key] = obj[key]
    }
  }
  return param
}

/**
 *  判断传入参数的类型，以字符串的形式返回
 *  @obj：数据
 **/
utils.dataType = (obj) => {
  if (obj === null) return 'Null'
  if (obj === undefined) return 'Undefined'
  return Object.prototype.toString.call(obj).slice(8, -1)
}

utils.MD5 = (str) => {
  return crypto.createHash('md5').update(str).digest('hex')
}

utils.MD5ForTimes = (str, times = 1) => {
  let encryptStr = ''
  for (let i = 0; i < times; i++) {
    if (encryptStr !== '') {
      encryptStr = crypto.createHash('md5').update(encryptStr).digest('hex')
    } else {
      encryptStr = crypto.createHash('md5').update(str).digest('hex')
    }
  }
  return encryptStr
}

const mobileRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i

// const tabletRE = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i;

utils.isMobile = (userAgent) => {
  var ua = userAgent
  if (typeof ua !== 'string') return false

  return mobileRE.test(ua)
}

/**
 * 获取两个时间段所有小时
 */
utils.getHours = (startTime, endTime = '') => {
  let hours = []
  let lastTime = moment(startTime).format('YYYY-MM-DD HH:00:00')
  const diffHours = moment(endTime).diff(lastTime, 'hours')
  if (diffHours > 0) {
    for (let i = 0; i < diffHours; i++) {
      const hour = moment(lastTime).add(i, 'hours').format('YYYY-MM-DD HH:00:00')
      hours.push(hour)
    }
  }
  return hours
}

// 获取时间
utils.getTime = () => {
  return moment().format('YYYY-MM-DD HH:mm:ss')
}

// 格式化时间
utils.formatTime = (time, strFromat = 'YYYY-MM-DD HH:mm:ss') => {
  if (!time || (utils.dataType(time) === 'String' && time.length === 0)) {
    return null
  }
  return moment(time).format(strFromat)
}

// 两个数组取交集
utils.arrayIntersection = (arr1, arr2) => {
  return arr2.filter(function (v) {
    return arr1.indexOf(v) !== -1 // 利用filter方法来遍历是否有相同的元素
  })
}

utils.sleep = async (time) => {
  return new Promise((resolve) => {
    return setTimeout(resolve, time)
  })
}

// utils.mp3Duration = async (path) => {
//   return new Promise((resolve, reject) => {
//     mp3Duration(path, function (err, duration) {
//       if (err) { reject(err.message) }
//       resolve(duration)
//     })
//   })
// }

// // var RPCClient = require('@alicloud/pop-core').RPCClient
// // var client = new RPCClient({
// //   accessKeyId: config.ISI.accessKeyId,
// //   accessKeySecret: config.ISI.accessKeySecret,
// //   endpoint: 'http://nls-meta.cn-shanghai.aliyuncs.com',
// //   apiVersion: '2019-02-28'
// // })
// // => returns Promise
// // => request(Action, params, options)

// // 获取
// let lastToken = {
//   token: 'token',
//   expire_time: '1970-01-01 00:00:00'
//   // expire_time: '2019-10-22 13:00:00'
// }
// // 获取智能语音交互token
// utils.getToken = async () => {
//   const diffHours = moment().diff(moment(lastToken.expire_time), 'hours')
//   // 距离失效时间1小时时，重新获取token
//   if (diffHours >= 0) {
//     console.log('重新获取token')
//     const res = await client.request('CreateToken')
//     lastToken.token = res.Token && res.Token.Id
//     lastToken.expire_time = res.Token && moment(res.Token.ExpireTime * 1000)
//   }
//   return lastToken.token
// }

// // 根据文字生成音频
// utils.text2AudioUrl = async (strText) => {
//   const result = {
//     cdnUrl: '',
//     duration: 0
//   }
//   if (!strText || strText.length === 0) {
//     return result
//   }
//   var appkey = config.ISI.appkey
//   var format = 'mp3'
//   const filename = utils.MD5(strText + Date.now()) + '.' + format
//   var sampleRate = 16000
//   const path = process.cwd() + '/uploads/' + filename

//   try {
//     const token = await utils.getToken()
//     await utils.processPOSTRequest(appkey, token, strText, path, format, sampleRate)
//     const upload = require('../controller/upload')
//     result.cdnUrl = await upload.uploadfile(path, format)
//     result.duration = await utils.mp3Duration(path)
//     result.duration = Math.floor(result.duration)
//   } catch (error) {
//     console.log('error', error)
//   }
//   fs.stat(path, function (err, stat) {
//     if (err) { console.log('file not found:', path) }
//     if (stat) {
//       fs.unlink(path, () => {})
//     }
//   })
//   return result
// }

// // 移除emoji
// utils.removeEmoji = (content) => {
//   return content.replace(/(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/g, '')
// }

// var http = require('http')
// // var options = { method: 'HEAD', host: 'cdn-news.jin10.com', port: 80, path: '/df7c1713-65cd-45d8-8263-af19a2dbeca21.jpg' }
// utils.getHeaders = (options) => {
//   return new Promise((resolve, reject) => {
//     var req = http.request(options, function (res) {
//       resolve(res.headers)
//     })
//     req.on('error', function (e) {
//       reject(e)
//     })

//     req.end()
//   })
// }
